﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace Common
{
    /// <summary>
    /// Utility class for making sure the application is running with elevated permissions
    /// </summary>
    public static class RunAsAdmin
    {
        /// <summary>
        /// Checks if the application is running with elevated permission
        /// </summary>
        /// <returns>True if the application is running with elevated permission, false otherwise</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public static bool Check()
        {
            bool result = false;
            try
            {
                WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                result = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch (Exception e)
            {
                System.Console.Error.WriteLine(e);
            }
            return result;
        }

        /// <summary>
        /// Runs the specified application with elevated permissions
        /// </summary>
        /// <param name="exe">The aplication to run</param>
        public static void Run(String exe)
        {
            Contract.Requires(exe != null);
            ProcessStartInfo processInfo = new ProcessStartInfo();
            processInfo.Verb = "runas";
            processInfo.FileName = exe;
            Process.Start(processInfo);
        }
    }
}
